package sg.edu.nus.iss.billing.dao.login;

import java.util.ArrayList;

import sg.edu.nus.iss.billing.common.DbUtil;
import sg.edu.nus.iss.billing.common.Util;
import sg.edu.nus.iss.billing.common.exception.BadDaoCallException;
import sg.edu.nus.iss.billing.common.exception.BadDbCallException;
import sg.edu.nus.iss.billing.common.exception.InvalidParamsException;
import sg.edu.nus.iss.billing.vo.login.LoginVO;

public class LoginDAO implements ILoginDAO{
	private ArrayList<String> data = null;
	private final static String FILE_PATH = "data//user.txt";
	
	public LoginDAO() {
		try {
			data = (ArrayList<String>) DbUtil.loadDb(FILE_PATH);
		} catch (BadDbCallException e) {
			data = new ArrayList<String>();
			e.printStackTrace();
		}
	}
	
	private void createLogin (LoginVO login) throws BadDaoCallException  {
		data.add(login.serialised());
		try {
			DbUtil.saveDb(FILE_PATH, data);
		} catch (BadDbCallException e) {
			throw new BadDaoCallException("Unable to save login to db. " + e.getMessage());
		}
	}
	
	@Override
	public LoginVO getLoginMemberInfo(String memberId, String pw) {
		for(int i=0;i<data.size();i++) {
			LoginVO login = new LoginVO();
			try {
				login.setParameters(data.get(i));
				if (login.getUserID().equals(memberId) && login.getPassword().equals(pw)) {
					return login;
				}
			} catch (InvalidParamsException e) {
				// skip corrupted db entry
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public String getMemberRole(String memberId) {
		for(int i=0; i<data.size(); i++){
			LoginVO login = new LoginVO();
			try {
				login.setParameters(data.get(i));
				if (login.getUserID().equals(memberId)) {
					return login.getUserRole();
				}
			} catch (InvalidParamsException e) {
				// skip corrupted db entry
				e.printStackTrace();
			}
		}
		return Util.LOGIN_ROLE_UNKNOWN;
	}
	
	public void test() {
		LoginVO l = new LoginVO();
		l.setUserID("admin");
		l.setPassword("password");
		l.setUserRole("admin");
		try {
			createLogin(l);
		} catch (BadDaoCallException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DbUtil.printDb(data);
	}

	//Vipul
	@Override
	public LoginVO getLoginMemberInfo(LoginVO result) {
		String memberId = result.getUserID();
		String pw = result.getPassword();
		for(int i=0;i<data.size();i++) {
			LoginVO login = new LoginVO();
			try {
				login.setParameters(data.get(i));
				if (login.getUserID().equals(memberId) && login.getPassword().equals(pw)) {
					result.setUserRole(login.getUserRole());
				}
			} catch (InvalidParamsException e) {
				// skip corrupted db entry
				e.printStackTrace();
			}
		}
		return result;
	}
}
